﻿<!-- 综合监控页面 -->

<div id="map_box" class ="baidu-maps" style="width: 100%;height: 100%"></div>
<!-- 报警设置表单开始 -->
<form  class="layui-form layui-form-pane " action="" id="alarm_set_form" lay-filter="alarm_set_form" style="padding: 10px;display: none;">
  <div class="layui-form-item" style="display: none;">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">设备编号</label>
      <div class="layui-input-inline">
        <input readonly="" type="text" name="device_id" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">超速报警</label>
      <div class="layui-input-inline">
        <input type="text" name="speed_alarm"  placeholder="公里"  autocomplete="off" class="layui-input">
      </div>
      <div class="layui-form-mid layui-word-aux">KM/H</div>
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">停留报警</label>
      <div class="layui-input-inline">
        <input type="text" name="stop_rate"  placeholder="分钟"  autocomplete="off" class="layui-input">
      </div>
      <div class="layui-form-mid layui-word-aux">分钟</div>
    </div>
  </div>

  <div class="layui-form-item">
    <button class="layui-btn layui-btn-fluid" lay-submit="" lay-filter="set_param_submit">提交</button>
  </div>
</form>

<!-- 报警设置表单结束 -->


<!-- 命令下发弹窗开始 -->
<!-- 命令下发表格的执行按钮 -->
<script type="text/html" id="command_table_bar">
    <a class="layui-btn layui-btn-xs" lay-event="excue_command">执行</a>
</script>

  <table class="layui-table" id="command_down_table"  lay-filter="command_table_filter" style="padding: 0px 0px 0px 0px;margin: 0px 0px 0px 0px;display: none;">
  </table>

<!-- 命令下发弹窗结束 -->

<!-- 硬件参数设置开始 -->
<form  class="layui-form layui-form-pane " action="" id="param_set_form" lay-filter="param_set_form" style="padding: 10px;display: none;">
  <div class="layui-form-item" style="display: none;">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">设备编号</label>
      <div class="layui-input-inline">
        <input id="set_device_id" readonly="" type="text" name="device_id" autocomplete="off" class="layui-input">
      </div>
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">回传间隔</label>
      <div class="layui-input-inline">
        <input id="send_rate" type="text" name="send_rate"  placeholder="秒" value="30"  autocomplete="off" class="layui-input">
      </div>
      <div class="layui-form-mid layui-word-aux">秒</div>
      <a class="layui-btn" onclick="device_set('send_rate',$('#set_device_id').val(),$('#send_rate').val())"><i class="layui-icon layui-icon-set" style="font-size: 12px"> 提交</i></a>
    </div>
  </div>
</form>

<!-- 硬件参数设置结束 -->


<!-- 手机用户绑定设备开始 -->
<form  class="layui-form layui-form-pane " action="" id="bind_dev_phoneuser" lay-filter="bind_dev_phoneuser" style="padding: 10px;display: none;">
  <div class="layui-form-item" style="color: white;font-size: 16px">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">设备ID</label>
      <div class="layui-input-inline">
        <input type="text" name="device_id" lay-verify="required" autocomplete="off" placeholder="设备ID" class="layui-input">
      </div>
    </div>
  </div>
   <div class="layui-form-item" style="color: white;font-size: 16px">
    <div class="layui-inline">
      <label class="layui-form-label layui-bg-green">授权码</label>
      <div class="layui-input-inline">
        <input type="text" name="auth_id" lay-verify="required"  placeholder="授权码"  autocomplete="off" class="layui-input">
      </div>
  </div>
  <button id="submit_btn" lay-submit lay-filter="bind_dev_phoneuser" style="display: none;">提交</button>
</form>
<!-- 手机用户绑定设备结束 -->
<!-- 百度地图的相关调用，定位打点，地址解析等 -->
<script type="text/javascript" src="/static/js/bd_map.js"></script>

<script type="text/javascript">

// $('.layui-side').show()
// $('.layui-body').attr('style','padding:0px;bottom:0px;top:60px;left:300px')
// ------侧边栏内容处理start--------//
// $('#side2').empty()
// $('#side2').attr('class','empty')
// $('.empty').hide()
// $('#side1').attr('class','layui-side')
// $('.layui-side').show()
// ------侧边栏内容处理end--------//

// ------手机注册用户绑定设备功能开始--------//
// console.log(character['bind_dev'],user_permi)
table.render()
form.render();

var ajax_url='dynamic'
var show_bind_dev_form=function(){
  layer.open({
    type: 1
    ,title:'绑定设备'
    ,area:['400px','240px']
    ,offset:'60px'  
    ,id: 'register_data' 
    ,content:$('#bind_dev_phoneuser')
    ,btn: ['提交','关闭']
    ,shade: 0 //不显示遮罩
    ,btn1: function(){
      $('#submit_btn').click()
      
    }
    ,btn2: function(){
      layer.closeAll();
    }
  }); 
}

form.on('submit(bind_dev_phoneuser)',function(obj){
  // console.log(obj.field)
  layer.closeAll()
  var param_data=obj.field
  $.ajax({
    type: 'POST',
    data:param_data,
    url:'/dynamic/?what=phone_user_bind_dev',
    async:true,
    dataType: 'json',
    success: function(data) {
      // console.log(JSON.stringify(data))
      if(data.code==1000){
        layer.msg('绑定设备成功')
        device_list_table(data.data)
      }else{
        alert(data.error)
      }
    },
  });
  return false
})

if(user_permi=='phone_user' && character['bind_dev']==null){
  show_bind_dev_form()
}
// ------手机注册用户绑定设备功能结束--------//

// 渲染树状用户结构，需要增加宽度，增加横向的滚动
tree.render({
    elem: '#id_tree'
    ,data: user_tree
    ,showCheckbox: false  //是否显示复选框
    ,onlyIconControl:true
    ,id: 'user_tree_id'
    ,isJump: true //是否允许点击节点时弹出新窗口跳转
    ,text: {
            defaultNodeName: '未命名' //节点默认名称
            ,none: '无数据' //数据为空时的提示文本
          }   
    // ,showLine:false
    ,click: function(obj){
      // 选择用户，展示该用户名下的设备
      var check_user = obj.data.name;
      var user_title= obj.data.title
      // 用户状态搜索展示
      user_check['name']=check_user
      user_check['title']=user_title
      var check_user_device=[];
      for(var i=0;i<device.length;i++){
         if(device[i]['owner']===check_user){
          check_user_device.push(device[i])
         }
      }
      if(check_user=='all'){
        device_list_table(device)
      }else{
        device_list_table(check_user_device)
      }
      dev_status_num(check_user,user_title)
    }
  });


// 设备列表框的高度处理
var dev_list_panle_height=get_height-330
// $('#dev_list_panle').attr('style','height:'+dev_list_panle_height+'px;overflow:auto')
// 设备列表数据加载函数
var device_list_table=function(table_data){
  // device=table_data
  table.render({
    elem: '#dev_list_show',
    data: table_data,
    id:'device_list',
    skin:'nob',
    size:'sm',
    height: 'full-330',
    cols: [[
        {type: "checkbox", fixed: "left"},
        {field: 'user_name', title: '名称'},
        {field: 'device_id', title: '设备ID',sort:true},
        {field: 'on_off_line', title: '状态',sort:true,templet: function(d){
          var status;
          if(d.on_off_line==='online'){
            status='在'
          }else{
            status='离'
          }
        return status
      }}
    ]],
    // page: true,
    limit:10000000
  });
}
device_list_table(device)

// 按照设备状态展示设备
// 全局变量user_check,用户存储用户树状图上被选中的用户name和title
var user_check={'name':'all','title':'全部'};
var device_status_search=function(dev_status){

  var user_name=user_check['name']

  var query_status={'online':'on_off_line','sleep':'sleep_status','offline':'on_off_line','alarm':'alarm_status'}

  var dev_status_list=[]

  for(var i=0;i<device.length;i++){

    if(user_name=='all'){
      if(dev_status=='all'){
        dev_status_list.push(device[i])
      }else{
        if(device[i][query_status[dev_status]]==dev_status){
          console.log('dev_status',dev_status)
          dev_status_list.push(device[i])
        }
      }
    }else{
      if(dev_status=='all'){
        if(device[i]['owner']==user_name){
          dev_status_list.push(device[i])
        }
      }else{
        if(device[i]['owner']==user_name && device[i][query_status[dev_status]]==dev_status){
          dev_status_list.push(device[i])
        }
      }
    }
  }

  device_list_table(dev_status_list)
}

// 某用户设备状态（在线，离线，报警，休眠）统计函数
var dev_status_num=function(user_name,user_title){
  var query_status={'online':'on_off_line','sleep':'sleep_status','offline':'on_off_line','alarm':'alarm_status'}
  var dev_status={}
  for(var k in query_status){
    dev_status[k]=[]
    for(var i=0;i<device.length;i++){
      if(user_name=='all'){
        if(device[i][query_status[k]]==k){
          dev_status[k].push(device[i])
        }
      }else{
        if(device[i]['owner']==user_name && device[i][query_status[k]]==k){
          dev_status[k].push(device[i])
        }
      }
    }
  } ;
  
  // 把各种状态设备的数量显示到相应的位置
  var status_show_dict={'online':'在线','sleep':'休眠','offline':'离线','alarm':'报警'}
  
  for(var k in dev_status){
    $('#dev_'+k).text(status_show_dict[k]+'('+dev_status[k].length.toString()+')')
  }
  // 某个用户的设备总数量
  var total_num=0;
  if(user_name=='all'){
    total_num=device.length
  }else{
    for(var i=0;i<device.length;i++){
      if(device[i]['owner']==user_name){
        total_num+=1
      }
    }
  }
  $('#user_chosed').text(user_title+'('+total_num.toString()+')')

  return dev_status
}

var dev_status_detail=dev_status_num('all','全部')

// 监听设备列表点击
// 存储被点击的设备对象的本页面全局变量
var checkDiv={};
table.on('row(dev_list_show)', function(obj){
  click_dev_id(obj)
  layer.closeAll()

});

// 页面数据刷新，局部刷新
var refresh_page=function(data){
  console.log('refresh')
  for(var i=0;i<data.length;i++){
    if(data[i]['device_id'] in checkDiv){
      data[i]["LAY_CHECKED"]=true
    }
    if(bd_map_marker_obj_list[data[i]['device_id']]){
      var m=bd_map_marker_obj_list[data[i]['device_id']]
      var pt=new BMap.Point(data[i].lng,data[i].lat)
      m.setPosition(pt)
      // map.closeInfoWindow()
      console.log(current_open_device_infowindow,data[i]['device_id'],current_open_device_infowindow==data[i]['device_id'])
      if(current_open_device_infowindow==data[i]['device_id']){
        // map.closeInfoWindow()
        open_device_infowindow(data[i],pt)
      }
    }
  }
  device=data
  device_list_table(data)
 
}

// get_info_ajax(ajax_url,'get_init_data',refresh_page)
interval_func=setInterval(function(){
  get_info_ajax(ajax_url,'get_init_data',refresh_page)
},param_refresh_time_control)


// -----点击设备链表，勾选功能--------//

var click_dev_id=function(obj){//选中行同步选中复选按钮
  var tr = obj.tr;
  var div = tr.find("div.layui-unselect");
  //checkDiv为定义的属性用来缓存当前点击的行是否选中状态，未选择的选中，选中的取消选中，并进行相应的地图打点处理
  // console.log(obj.data.device_id)
  if(!checkDiv[obj.data['device_id']]) {
    chosed_dev=obj.data
    checkDiv[obj.data['device_id']] = obj;
    div.addClass("layui-form-checked");
    add_device_marker_bdmap(obj.data)
  } else {
    div.removeClass("layui-form-checked");
    delete checkDiv[obj.data['device_id']];
    remove_marker_bdmap(obj.data['device_id'])
    chosed_dev={'device_id':'default'}
  }
  console.log(chosed_dev)
}



// 报警参数功能js部分开始
// 监听报警参数设置
var set_param=function(device_id,status){
  // console.log(chosed_dev)
  document.getElementById("alarm_set_form").reset();
  var param_set=chosed_dev.param_set
  if(param_set==0){
    param_set={}
  }
  // 把设备之前的参数设置赋值给form
  param_set.device_id=chosed_dev.device_id
  form.val("alarm_set_form",param_set)
  
  layer.open({
      type: 1
      ,title:'报警参数设置: '+device_id
      ,area:['400px','auto']
      ,offset:'100px'  
      ,id: 'add_data' //防止重复弹出
      ,content:$('#alarm_set_form')
      ,shade: 0 //不显示遮罩
    });
};
// 报警参数设置上传后台

form.on('submit(set_param_submit)', function (data) {
  // console.log(data)
  var result=data.field
  post_info_ajax(result,ajax_url,'alarm_set',device_list_table)
  return false;
});


// 报警参数功能js部分结束

// ------命令下发功能js部分开始-------//
 // 监听命令下发弹窗

console.log(dev_model)
var command_modal=function(device_id,status){
  // 重新组装可以加载到表格的命令数据格式
  console.log(dev_model_objs)
  var command_dict=dev_model_objs[chosed_dev.dynamic.receive_port[1]]
  if(!command_dict){
  	layer.msg('设备尚未启用')
  	return
  }else{
    command_dict=command_dict['command']
  }

  delete command_dict.unique_id
  var command_detail=[]
  for(k in command_dict){
    var comm_value={};
    if(command_dict[k]!='无'){
      comm_value['set_command']=k
      comm_value['set_value']='1'
      comm_value['command_name']=command_dict[k]
      comm_value['device_id']=device_id
      command_detail.push(comm_value)
    }
  }

   
    layer.open({
        type: 1
        ,title:false
        ,area:'220px'
        ,offset:'100px'  
        ,id: 'command_data' //防止重复弹出
        ,content:$('#command_down_table')
        ,shade: 0 //不显示遮罩
        ,success:function(layero,index){
            table.render({
            elem: '#command_down_table',
            data: command_detail,
            id:'command_down_table',
            skin:'nob',
            // size:'sm',
            cols: [[
                {field: 'device_id', title: '设备ID',hide:true},
                {field: 'command_name', title: '命令'},
                {field: 'set_value', title: '参数',hide:true},
                {field: 'set_command', title: '格式',hide:true},
                {title: '操作',templet: '#command_table_bar', fixed: "right", align: "center"}
            ]],
            page: false
          });
        }
      });

};


//命令下发到后台进行处理
table.on('tool(command_table_filter)', function (obj) {
  if(chosed_dev.on_off_line!=='online'){
    layer.msg('设备离线，无法执行该指令')
    // return false
  }
  var result = obj.data;
  delete result.command_name
  result.send_time=$('#get_current_time').text()
  result.port=chosed_dev.dynamic.receive_port
  console.log(result)
  post_info_ajax(result,ajax_url,'order_dowm')

});
// ------命令下发功能end-------//


var sos_detail={};
var time_remind_data={};
var device_set_modal=function(device_id,status){
  // 因为动态加载form，需要主动渲染form，解决select不显示的问题
  document.getElementById("param_set_form").reset();
  // console.log(chosed_dev)
  var param_set=chosed_dev.param_set
  if(param_set==0){
    param_set={}
  }
  // 把设备之前的参数设置赋值给form
  param_set.device_id=chosed_dev.device_id
  form.val('param_set_form',param_set)

  // 弹出弹窗
  parent.layer.open({
    type: 1
    ,title:'硬件参数设置: '+device_id
    ,area:'480px'
    ,offset:'100px'  
    ,id: 'command_data' //防止重复弹出
    ,content:$('#param_set_form')
    ,zIndex:999
    // 遮罩把弹窗盖住的问题的解决办法，把遮罩和弹窗放在同一层
    // ,success:function(layero){
    //   console.log(layero)
    //      var mask = $(".layui-layer-shade");
    //      mask.appendTo(layero.parent());
    //      //其中：layero是弹层的DOM对象
    // }
    ,shade: 0 //不显示遮罩
  });
}


// 监听用户输入设备设置参数并提交后台
var device_set=function(set_command,device_id,set_value){
  var base_info={}
  base_info.device_id=device_id
  base_info.set_command=set_command
  base_info.set_value=set_value
  base_info.send_time=$('#get_current_time').text()
  base_info.port=chosed_dev.dynamic.receive_port
  post_info_ajax(base_info,ajax_url,'device_set')
  return false
}

// 设备参数设置功能js部分结束



</script>